import {useEffect,useState} from 'react'
// import {fromEvent} from 'rxjs'
// import { take } from 'rxjs/operators';
import './index.css'
 const userData = [
  { id: 1, name: "Martin", type: "Manager" },
  { id: 2, name: "Alex", type: "developer" },
  { id: 3, name: "Bob", type: "client" },
];


const getMockUserData = (id) => {
  return new Promise((resolve, reject) => {
    let user = userData.find((u) => u.id === id)
    if (user) {
        // 模拟接口请求
        setTimeout(() => resolve(user), Math.random() * 3000);
    } else {
        setTimeout(() => reject('user not found'), Math.random() * 3000);
    }
  });
};

const User = () => {
  const [user, setUser] = useState(1);
  const [data, setData] = useState("");
  const [loading, setLoading] = useState(false);

  // fromEvent(document.body,'click').subscribe(e => {
  //   console.log(e,'kjk')
  // })

  useEffect(() => {
      let canceled = true
    setLoading(true);
    getMockUserData(user).then(
      (data) => {
        console.log(canceled,'cancel http')
          if(canceled) {
            setData(data);
            setLoading(false);
          }
      },
      (error) => {
        console.log(error);
      }
    );

    // js 实现监听点击事件，只监听一次
    // let count = 0
    // const handler = e => {
    //     count += 1
    //     console.log(`监听点击事件${count}次`)
    //     document.body.removeEventListener('click', handler)
    // }
    // document.body.addEventListener('click',handler)



    return () =>{
      canceled = false
      console.log(canceled,'cancel return')
    }
  }, [user]);

  return (
    <div className="button-wrapper">
      <button className="mr-s mb-s" onClick={()=>setUser(1)}>Bob</button>
      <button className="mr-s mb-s" onClick={() => setUser(2)}>Alex</button>
      <button className="mr-s mb-s" onClick={() => setUser(3)}>Martin</button>
      <div className="mb-s">{`Active User id ${user}`}</div>
      <div>{loading ? "Loading...." : JSON.stringify(data, null, 4)}</div>
    </div>
  );
}
export default User;
